<template>
  <div class="umsUser-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
      width="550px"
    >
      <div style="padding-right: 50px; padding-top: 20px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="版本号" prop="version">
            <el-input
              placeholder="请输入当前版本"
              v-model="modelValue.form.version"
            />
          </el-form-item>
          <el-form-item label="应用平台" prop="platformId">
            <el-select
              v-model="modelValue.form.platformId"
              placeholder="请选择应用平台"
              style="width: 100%"
            >
              <el-option
                v-for="option in modelValue.platFormList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="
              modelValue.form.platformId >= 1 && modelValue.form.platformId <= 3
            "
            label="固件上传"
            prop="file"
          >
            <el-upload
              style="width: 100%"
              ref="uploadRef"
              class="upload-demo"
              :before-upload="canUpload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :auto-upload="false"
              drag
              action="/settingservice/systems/version/file"
              :on-change="handleFileChange"
              :file-list="modelValue.form.fileList"
              :headers="uploadHeaders"
            >
              <div class="update-demo-content">
                <div>
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                </div>
                <div class="el-upload__text">
                  将文件拖到此处, 或<em>点击上传</em>
                </div>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              v-model="modelValue.form.remark"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { addUser, updateUser } from '@/api/user.api'
import { ElMessage, ElUpload, ElIcon, FormInstance } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { addVersion, addVersionByFile } from '@/api/sys-version-manage.api'

const props = defineProps(['modelValue'])

const uploadRef = ref()
const addEditRef = ref<FormInstance>()
const canUpload = async (rawFile) => {
  let name = rawFile.name
  let index = name.lastIndexOf('.')
  let exet = name.substring(index + 1)

  if (!(exet === 'bin')) {
    ElMessage({
      message: '只接受固件升级文件',
      type: 'error',
    })
    return false
  }
  return true
}

const handleFileChange = (file) => {
  props.modelValue.form.fileList.push(file)
  console.log('当前文件:', file.raw) // 关键：获取原始文件对象
}

const uploadHeaders = {
  token: localStorage.getItem('TOKEN'),
}

const uploadError = (err, file, fileList) => {
  ElMessage({
    message: err.msg || err,
    type: 'error',
  })
}

const uploadSuccess = (response, file, fileList) => {
  ElMessage({
    message: '图片上传成功',
    type: 'success',
  })
  return
}

/***
 * 确认弹框
 */
const ensure = () => {
  let form = props.modelValue.form
  let formData = {
    version: form.version,
    platformId: form.platformId,
    platformName: form.platformName,
    remark: form.remark,
  }

  //根据 platformId 获得 platformName
  let platFormList = props.modelValue.platFormList || []
  let platFormItem = platFormList.find((item) => item.id == form.platformId)
  if (platFormItem) {
    formData.platformName = platFormItem.name
  }

  if (formData.platformId > 3) {
    updateVersion(formData)
    return
  }
  updateVersionWithFile(formData)
}

const updateVersion = (formData: any) => {
  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      addVersion(formData)
        .then((res) => {
          cancel()
          ElMessage({
            message: props.modelValue.title + '新增成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

const updateVersionWithFile = (formData: any) => {
  const formData1 = new FormData()
  formData1.append('version', formData.version)
  formData1.append('platformId', formData.platformId)
  formData1.append('platformName', formData.platformName)
  formData1.append('remark', formData.remark)

  let fileList = props.modelValue.form.fileList || []
  console.log('fileList:', fileList[0])
  formData1.append('file', fileList[0].raw)

  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      addVersionByFile(formData1)
        .then((res) => {
          cancel()
          ElMessage({
            message: props.modelValue.title + '新增成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false
}
</script>

<style lang="scss" scoped>
.update-demo-content {
  display: flex;
  flex-direction: column;
}
</style>
